package com.itany.mall.dao.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.itany.mall.dao.OrderDao;
import com.itany.mall.entity.Order;
import com.itany.mall.exception.DataAccessException;
import com.itany.mall.factory.Component;

import database.Database02;

@Component
public class OrderDaoImpl implements OrderDao {

	@Override
	public long insert(Order order) {
		try {
			order.setId(Database02.autoIncrement(Database02.ORDER_DIR));

			File f = new File(Database02.ORDER_DIR, order.getId() + Database02.ORDER_SUFFIX);
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
			oos.writeObject(order);
			oos.flush();
			oos.close();

			return order.getId();
		} catch (IOException e) {
			throw new DataAccessException(e);
		}
	}

	@Override
	public List<Order> selectByUserId(long userId) {
		List<Order> list = new ArrayList<>();

		File dir = new File(Database02.ORDER_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.ORDER_SUFFIX);
			}
		});

		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				Order o = (Order) ois.readObject();
				ois.close();
				if (o.getUser().getId().equals(userId)) {
					list.add(o);
				}
			}
			return list;
		} catch (Exception e) {
			throw new DataAccessException(e);
		}
	}

	@Override
	public Order selectByNumAndUserId(String num, long userId) {
		File dir = new File(Database02.ORDER_DIR);
		File[] fs = dir.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(Database02.ORDER_SUFFIX);
			}
		});

		try {
			for (File f : fs) {
				ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
				Order o = (Order) ois.readObject();
				ois.close();
				if (o.getOrderNum().equals(num) && o.getUser().getId().equals(userId)) {
					return o;
				}
			}
			return null;
		} catch (Exception e) {
			throw new DataAccessException(e);
		}
	}

}
